package com.ncmmall.mall.controller.business.merchant;

import com.ncmmall.application.business.merchant.MerchantApplication;
import com.ncmmall.application.securitys.logs.OperationLogApplication;
import com.ncmmall.application.util.WechatMessageUtils;
import com.feijin.commons.exceptions.IllegalRequestException;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.merchant.MerchantGoodsChannel;
import com.ncmmall.domain.business.merchant.QMerchantGoodsChannel;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author linxs
 * @Description: 商家审核管理
 * @Date: 2019-06-26 20:24
 */
@Controller
@RequestMapping(value = "/mall/merchant/check")
public class MerchantCheckController {

    private final static Logger logger = LoggerFactory.getLogger(MerchantCheckController.class);

    @Value("${web.domain}")
    private String webDomain;

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantApplication merchantApplication;

    @Autowired
    private OperationLogApplication logApplication;


    /**
     * 分页条件筛选
     *
     * @param model
     * @param pageParams
     * @param merchant
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, WebUser merchant) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        String hql = builderSQL("select u from WebUser u where u.role.name = 'MERCHANT' ", params, merchant);
        QueryPage<WebUser> page = queryChannelService.findPage(hql, pageRequest.setParams(params), WebUser.class);
        model.addAttribute("page", page).addAttribute("params", merchant);

        return "mall/merchant/check/list";
    }

    /**
     * 查看商家详情
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/detail", method = RequestMethod.GET)
    private String detail(Model model, @PathVariable("id") long id) {

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);
        model.addAttribute("merchant", merchant).addAttribute("channels", queryChannelService.findAll(QMerchantGoodsChannel.merchantGoodsChannel.merchant.id.eq(id), MerchantGoodsChannel.class));

        return "mall/merchant/check/detail";
    }

    /**
     * 审核商家信息
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}/info", method = RequestMethod.GET)
    private String check(Model model, @PathVariable("id") long id) {

        WebUser merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(id), WebUser.class);
        model.addAttribute("merchant", merchant).addAttribute("_method", "PUT");

        return "mall/merchant/check/check";
    }

    /**
     * 审核商家信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/{id}/info", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> check(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, @ModelAttribute WebUser merchant) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalRequestException("request must be ajax !");
            }

            merchantApplication.checkMerchant(merchant);
            logApplication.eventOfSystem(Securitys.currentUser(), "审核商家信息", Securitys.getIp(request));

            merchant = queryChannelService.findOne(QWebUser.webUser.id.eq(merchant.getId()), WebUser.class);

            JSONObject item = new JSONObject();
            item.put("thing2", JSONObject.fromObject(ImmutableMap.of("value", merchant.getShopName())));
            item.put("thing1", JSONObject.fromObject(ImmutableMap.of("value", merchant.getRealName())));
            item.put("phone_number3", JSONObject.fromObject(ImmutableMap.of("value", merchant.getMobile())));

            if (merchant.getMerchantCheckStatus() == 2) {
                item.put("phrase4", JSONObject.fromObject(ImmutableMap.of("value", "通过")));
            } else if (merchant.getMerchantCheckStatus() == 3) {
                item.put("phrase4", JSONObject.fromObject(ImmutableMap.of("value", "不通过")));
            }

            try {
                WechatMessageUtils.send(merchant.getRelevanceMember().getOpenId(), "b70tDNYYFtpQ7eOZr_0ZB_0jWSemeFXH208lA18PFMY", item.toString());

            } catch (Exception e) {
                //do nothing...
            }


            return ImmutableMap.of("status", true);
        } catch (Exception e) {
            logger.error("[审核商家信息异常]", e);
            return ImmutableMap.of("status", false);
        }
    }

    /**
     * 条件查询
     *
     * @param sql
     * @param params
     * @param merchant
     * @return
     */
    private String builderSQL(String sql, Map<String, Object> params, WebUser merchant) {

        if (!Strings.isNullOrEmpty(merchant.getRealName())) {
            sql += " and u.realName like :realname ";
            params.put("realname", "%" + merchant.getRealName() + "%");
        }

        if (!Strings.isNullOrEmpty(merchant.getMobile())) {
            sql += " and u.mobile like :mobile ";
            params.put("mobile", "%" + merchant.getMobile() + "%");
        }

        if (!Strings.isNullOrEmpty(merchant.getUsername())) {
            sql += " and u.username like :username ";
            params.put("username", "%" + merchant.getUsername() + "%");
        }

        if (!Strings.isNullOrEmpty(merchant.getShopName())) {
            sql += " and u.shopName like :shopname ";
            params.put("shopname", "%" + merchant.getShopName() + "%");
        }

        if (merchant.getMainType() > 0) {
            sql += " and u.mainType = :maintype ";
            params.put("maintype", merchant.getMainType());
        }

        if (merchant.getMerchantCheckStatus() > 0) {
            sql += " and u.merchantCheckStatus = :status ";
            params.put("status", merchant.getMerchantCheckStatus());
        }

        if (!Strings.isNullOrEmpty(merchant.getOrderByGoodsNumber())) {
            sql += " order by u.goodsNumber " + merchant.getOrderByGoodsNumber();
        } else if (!Strings.isNullOrEmpty(merchant.getOrderByMerchantEnterTime())) {
            sql += " order by u.merchantEnterTime " + merchant.getOrderByMerchantEnterTime();
        } else if (!Strings.isNullOrEmpty(merchant.getOrderByTotalOrderAmount())) {
            sql += " order by u.totalOrderAmount " + merchant.getOrderByTotalOrderAmount();
        } else if (!Strings.isNullOrEmpty(merchant.getOrderByTotalOrderNumber())) {
            sql += " order by u.totalOrderNumber " + merchant.getOrderByTotalOrderNumber();
        } else {
            sql += " order by u.createTime desc ";
        }

        return sql;
    }


}
